package com.siyoumi.app.test.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Envelope;
import com.siyoumi.app.rabbitmq.RabbitMqConsumer;
import com.siyoumi.component.XApp;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

//直接队列
@Slf4j
public class RabbitMqConsumerDirect
        extends RabbitMqConsumer {
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        String message = new String(body, StandardCharsets.UTF_8);
        log.debug("message: {}", message);

        int rnd = XApp.random(0, 10);
        if (rnd > 5) {
            log.debug("确认消息-成功");
            getChannel().basicAck(envelope.getDeliveryTag(), false);
        } else {
            log.debug("确认消息-失败-重发");
            //参数2:true:重发;false:丢弃
            getChannel().basicReject(envelope.getDeliveryTag(), true);
        }
    }

    //static public RabbitMqConsumer getIns(RabbitMqConfig config) {
    //    RabbitMqConsumer mq = new RabbitMqConsumerDirect();
    //    mq.init(config);
    //    return mq;
    //}
    //
    //@Override
    //protected String getQueueName() {
    //    return "def_queue";
    //}
    //
    //@Override
    //protected Consumer consumerHandle() {
    //    // 创建队列消费者
    //    return new DefaultConsumer(getChannel()) {
    //        @SneakyThrows
    //        @Override
    //        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
    //            String message = new String(body, StandardCharsets.UTF_8);
    //            log.debug("message: {}", message);
    //
    //            int rnd = XApp.random(0, 10);
    //            if (rnd > 5) {
    //                log.debug("确认消息-成功");
    //                getChannel().basicAck(envelope.getDeliveryTag(), false);
    //            } else {
    //                log.debug("确认消息-失败-重发");
    //                //参数2:true:重发;false:丢弃
    //                getChannel().basicReject(envelope.getDeliveryTag(), true);
    //            }
    //        }
    //    };
    //}
}